package org.holynite.fieldmanage.repositories.impl

import org.holynite.fieldmanage.entities.ChargeRule
import org.holynite.fieldmanage.persistence.ChargeRuleEAO
import org.holynite.fieldmanage.repositories.BaseEAO

import javax.ejb.Stateless

/**
 * Created by midnite on 15/1/25.
 */
@Stateless(name = "chargeRuleEao")
class ChargeRuleEAOImpl extends BaseEAO implements ChargeRuleEAO {
	@Override
	List<ChargeRule> listAllRulesInScheme(String scheme) {
		def query = em.createQuery("select cr from ChargeRule as cr where cr.schemeId=:schId order by cr.begin asc, cr.end desc")
		query.setParameter("schId", scheme)
		query.resultList
	}

	@Override
	List<ChargeRule> searchRulesInScheme(String scheme, String keyword) {
		def query = em.createQuery("select cr from ChargeRule as cr where cr.schemeId=:schId and cr.name like :keyword order by cr.begin asc, cr.end desc")
		query.setParameter("schId", scheme).setParameter("keyword", "%$keyword%".toString())
		query.resultList
	}

	@Override
	ChargeRule findRule(String scheme, String ruleId) {
		def query = em.createQuery("select cr from ChargeRule as cr where cr.schemeId=:schId and cr.ruleId=:crId")
		query.setParameter("schId", scheme).setParameter("crId", ruleId)
		query.singleResult as ChargeRule
	}

	@Override
	void removeAllRulesInScheme(String scheme) {
		def query = em.createQuery("delete from ChargeRule as cr where cr.schemeId=:schId")
		query.setParameter("schId", scheme)
		query.executeUpdate()
	}

	@Override
	void removeRuleInScheme(String scheme, String ruleId) {
		def query = em.createQuery("delete from ChargeRule as cr where cr.schemeId=:schId and cr.ruleId=:ruleId")
		query.setParameter("schId", scheme).setParameter("ruleId", ruleId)
		query.executeUpdate()
	}
}
